#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2021/11/28 下午7:05
    Desc  :
--------------------------------------
"""
import json

from django.core.paginator import Paginator
from django.db import transaction
from django.urls import path
from django.utils.decorators import method_decorator
from django_http_log.common.request import BaseAPIView
from django_http_log.common.response import SuccessResponse, CommonResponse, ParamsErrorResponse, \
    SystemExceptionResponse
from django_http_log.decorator.auth import check_param

from common.decorator.token_decorator import isAuthentication
from common.enums.response_enums import CommonResultEnums
from common.utils.jwt_utils import JwtUtil, AuthJwt
from common.utils.log_utils import logger
from person.models.person import Application
from person.serializers.auth import ApplicationSerializer
from platform_auth.settings import APIDOC_DECORATOR


class AuthBaseAPIView(BaseAPIView):
    Model = Application

    serializer_class = ApplicationSerializer


class GetAppInfoAPIView(AuthBaseAPIView):
    def post(self, request, *args, **kwargs):
        pass


class CheckTokenAPIView(AuthBaseAPIView):
    """
    @author:    JiChao_Song
    @desc:      校验token是否有效
    @date:      2021/11/29 17:10
    """

    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'auth', desc = '鉴权管理')
    @APIDOC_DECORATOR.ApiOperation(summary = '校验token', path = '/auth/checkToken', method = "POST")
    @APIDOC_DECORATOR.ApiParams(value = 'appId', type = 'string', require = True, desc = '应用id')
    @APIDOC_DECORATOR.ApiParams(value = 'token', type = 'string', require = True, desc = 'token', )
    @method_decorator(isAuthentication(flag = True))
    def post(self, request, *args, **kwargs):
        try:
            authJwt = AuthJwt(request = request)

            flag = authJwt.verify_jwt()
            if flag is None:
                return CommonResponse(codeEnums = CommonResultEnums.TOKEN_INVALID)
            return SuccessResponse(result = flag)

        except Exception as e:
            logger.error(e)
            return SystemExceptionResponse()

    @method_decorator(check_param(paramsList = ['appId', 'token']))
    def get(self, request, *args, **kwargs):
        try:

            authJwt = AuthJwt(request = request)

            flag = authJwt.verify_jwt()
            if flag is None:
                return CommonResponse(codeEnums = CommonResultEnums.TOKEN_INVALID)
            return SuccessResponse(result = flag)
        except Exception as e:
            logger.error(e)
            return SystemExceptionResponse()


class GetTokenAPIView(AuthBaseAPIView):
    """校验token"""

    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'auth', desc = '鉴权管理')
    @APIDOC_DECORATOR.ApiOperation(summary = '获取token', path = '/auth/getToken', method = "POST")
    @method_decorator(isAuthentication(flag = True))
    def post(self, request, *args, **kwargs):
        try:
            appId = request.data.copy().get('appId')
            userInfo = request.data.copy().get('userInfo')

            queryset = self.Model.objects.filter(appId = appId, deleted = False)

            if queryset.count == 0:
                c = CommonResultEnums.APPLICATION_NOT_EXIST_BY_APPID
                c.message = f'appId={appId}不存在'
                return CommonResponse(codeEnums = c)

            flag = JwtUtil(secret = queryset.first().appSecret).generate_jwt(userInfo)
            return SuccessResponse(result = {
                'token': flag
            })

        except Exception as e:
            logger.error(e)
            return SystemExceptionResponse()


class ApplicationAddAPIView(AuthBaseAPIView):
    @transaction.atomic
    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'auth', desc = '鉴权管理')
    @APIDOC_DECORATOR.ApiOperation(summary = '新增应用', path = '/auth/addApply', method = "POST")
    @APIDOC_DECORATOR.ApiParams(value = 'appId', type = 'string', require = True, desc = '应用id')
    @APIDOC_DECORATOR.ApiParams(value = 'appName', type = 'string', require = True, desc = '应用名称')
    @APIDOC_DECORATOR.ApiParams(value = 'appIcon', type = 'string', desc = '应用图标')
    @APIDOC_DECORATOR.ApiParams(value = 'appDesc', type = 'string', desc = '应用描述')
    @method_decorator(isAuthentication(flag = True))
    def post(self, request, *args, **kwargs):
        try:
            data = request.data.copy()

            queryset_1 = self.Model.objects.filter(appId = data.get('appId'), deleted = False)

            if queryset_1.count() != 0:
                return CommonResponse(codeEnums = CommonResultEnums.APPLICATION_EXIST_BY_APPID)

            queryset_2 = self.Model.objects.filter(appName = data.get('appName'), deleted = False)

            if queryset_2.count() != 0:
                return CommonResponse(codeEnums = CommonResultEnums.APPLICATION_EXIST_BY_APPNAME)

            serializer = self.get_serializer(data = data, exclude = self.exclude_fields)
            if not serializer.is_valid():
                logger.error(f'创建用户失败--{serializer.errors}')
                return ParamsErrorResponse(message = serializer.errors, code = 40002)

            self.preform_create(serializer)

            return SuccessResponse(result = serializer.data)

        except Exception as e:
            logger.error(e)
            return SystemExceptionResponse()


class ApplicationListView(AuthBaseAPIView):
    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'auth', desc = '鉴权管理')
    @APIDOC_DECORATOR.ApiOperation(summary = '应用列表', path = '/auth/listApply', method = "POST")
    @APIDOC_DECORATOR.ApiParams(value = 'pageSize', type = 'string', require = True, desc = '每页数量')
    @APIDOC_DECORATOR.ApiParams(value = 'pageIndex', type = 'string', require = True, desc = '页码')
    @method_decorator(isAuthentication(flag = True))
    def post(self, request, *args, **kwargs):
        try:
            pageIndex, pageSize = request.data.get('pageIndex'), request.data.get('pageSize')
            if len(self.search_fields) != 0:
                queryset = self.Model.objects.filter(**self.search_queryset(request), deleted = False)
            else:
                queryset = self.Model.objects.filter(deleted = False)

            serializer = self.get_serializer(queryset, many = True, exclude = self.exclude_fields)
            pageData = Paginator(serializer.data, pageSize)
            data = {
                'totalSize': pageData.count,
                'pageIndex': pageIndex,
                'pageSize': pageSize,
                'array': pageData.page(pageIndex).object_list
            }

            return SuccessResponse(result = data)
        except Exception as e:
            logger.error(e)
            return SystemExceptionResponse()

    @method_decorator(check_param(paramsList = ['pageSize', 'pageIndex']))
    def get(self, request, *args, **kwargs):
        try:
            pageIndex, pageSize = request.query_params.get('pageIndex'), request.query_params.get('pageSize')
            if len(self.search_fields) != 0:
                queryset = self.Model.objects.filter(**self.search_queryset(request), deleted = False)
            else:
                queryset = self.Model.objects.filter(deleted = False)

            serializer = self.get_serializer(queryset, many = True, exclude = self.exclude_fields)
            pageData = Paginator(serializer.data, pageSize)
            data = {
                'totalSize': pageData.count,
                'pageIndex': pageIndex,
                'pageSize': pageSize,
                'array': pageData.page(pageIndex).object_list
            }

            return SuccessResponse(result = data)
        except Exception as e:
            logger.error(e)
            return SystemExceptionResponse()


class ApplicationEditAPIView(AuthBaseAPIView):
    @transaction.atomic
    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'auth', desc = '鉴权管理')
    @APIDOC_DECORATOR.ApiOperation(summary = '编辑应用', path = '/auth/editApply', method = "POST")
    @APIDOC_DECORATOR.ApiParams(value = 'appId', type = 'string', require = True, desc = '应用id')
    @APIDOC_DECORATOR.ApiParams(value = 'appName', type = 'string', require = True, desc = '应用名称')
    @APIDOC_DECORATOR.ApiParams(value = 'appIcon', type = 'string', desc = '应用图标')
    @APIDOC_DECORATOR.ApiParams(value = 'appDesc', type = 'string', desc = '应用描述')
    @method_decorator(isAuthentication(flag = True))
    def post(self, request, *args, **kwargs):
        pass


urlpatterns = [
    path('checkToken', CheckTokenAPIView.as_view()),
    path('getToken', GetTokenAPIView.as_view()),
    path('addApply', ApplicationAddAPIView.as_view()),
    path('listApply', ApplicationListView.as_view()),
]
